<?php
namespace app\common\model;

use think\Model;
use think\Session;
use app\common\model\Role as RoleModel;
use app\common\model\Permission as PermissionModel;

class Admin extends Model{
    /**
     * 后台用户权限数组
     * @var array
     */
    public $permission = [];
    /**
     * 加密盐值 不能随便改 专用于本model
     * @var string
     */
    protected static $salt = 'yangjifangshitiancai';


    public static function encrypt($key){
        return md5(self::$salt.$key);
    }

    public function login($username,$password){
        $where = [];
        $where['username']=$username;
        $where['password'] = self::encrypt($password);
        $where['state'] = 1;
        $admin = $this->where($where)->find();
        $result = ['state'=>0,'code'=>'','msg'=>''];
        if($admin){
            $admin->permission = $this->getPermission($admin->role);
            Session::set('admin',$admin);
        }else{
            $result['state'] = 1;
        }

        return $result;
    }


    /**
     * 通过admin 找到角色 找到权限
     * @param $role
     * @return mixed
     * @throws
     */
    protected function getPermission($role){
        //游客直接不让访问
        if(empty($role)){
            return [];
        }

        $role = RoleModel::get($role);
        $permission = PermissionModel::where('id','in',$role->permission)->column("url");
        return $permission;
    }



    /**
     * 用户的所有权限
     */
    public function permissions(){

    }

    /**
     * 判断是否拥有某个权限
     * 当前平台一个用户只有一个角色 所以只要判断权限就行了 不要对角色做判断
     */
    public function hasPermission($permission){
        $permissions = $this->getPermission($this->role);
        if(in_array($permission,$permissions)){
            return true;
        }
        return false;
    }

    /**
     * 判断是否拥有某个角色
     * @param $role
     */
    public function hasRole($role){

    }


    /**
     *
     * @param $role
     */
    public function isRole($role){

    }

}